package com.yonyou.wdt.job;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yonyou.wdt.entity.OpenApiURLEnum;
import com.yonyou.wdt.entity.QueryDto;
import com.yonyou.wdt.job.config.BaseConfig;
import com.yonyou.wdt.service.YonsuiteService;
import com.yonyou.wdt.utils.DateUtils;
import com.yonyou.wdt.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @ClassName YsProductToRedisJob
 * @Description YS物料档案信息同步Redis
 * @Author HuangWb
 * @Date 2023/5/12 18:35
 * @Version 1.0
 */
@Component
public class YsProductToRedisJob extends BaseConfig {


    private static Logger logger = LoggerFactory.getLogger(YsProductToRedisJob.class);

    @Resource
    private YonsuiteService yonsuiteService;

    private static final String JOB_CLASS="longPai003";
    @XxlJob("YsProductToRedisJob")
    public ReturnT<String> ysProductToRedisJob(String params) throws Exception {
        String param = XxlJobHelper.getJobParam();
        Map<String, Object> wlParam = new HashMap<>();
        if (param != null && !"".equals(param)) {
            List<String> timeRange = Arrays.asList(param.split("\\|"));
            if (timeRange.size() == 2) {
                wlParam.put("beganTime", timeRange.get(0));
                wlParam.put("endTime", timeRange.get(1));
            } else {
                wlParam.put("productCode", timeRange.get(0));
            }
        } else {
            // 默认查询前一天的数据
            wlParam.put("beganTime", DateUtils.getStartDateBy10m());
            wlParam.put("endTime", DateUtils.getEndDateBy10m());
        }
        // 处理相关业务
        QueryDto dto = new QueryDto();
        dto.setTenantId(getYsTenantId());
        dto.setAppKey(getYsAppKey());
        dto.setAppSecret(getYsAppSecret());
        // 获取YS系统租户动态域名信息
        ReturnT<String> isReturn2 = getYsDynamicDomainName(JOB_CLASS,dto);
        // 域名获取失败
        if (isReturn2 != null) return isReturn2;
        wlParam.put("pageIndex", 1);
        wlParam.put("pageSize", 100);
        boolean isNext = true;
        List<JSONObject> list = new ArrayList();
        int error = 0;
        int pageIndex = 1;
        while (true) {
            wlParam.put("pageIndex", pageIndex);
            JSONObject allocationRes = yonsuiteService.ysProductQuery(wlParam, dto);
            if (allocationRes.getStr("code").equals("200")) {
                if (null != allocationRes.getJSONObject("data") && null != allocationRes.getJSONObject("data").getJSONArray("recordList")) {
                    JSONArray purJSONArray = allocationRes.getJSONObject("data").getJSONArray("recordList");
                    for (Object allocation : purJSONArray) {
                        JSONObject allocationJson = (JSONObject) allocation;
                        HashMap<String, Object> detailMap = new HashMap<>(2);
                        detailMap.put("productCode", allocationJson.getStr("code"));
                        detailMap.put("orgId", allocationJson.getStr("createOrgId"));
                        ArrayList<Map<String, Object>> mapList = new ArrayList<>();
                        mapList.add(detailMap);
                        JSONObject detailRes = yonsuiteService.ysProductDetailNewQuery(mapList, dto);
                        if (detailRes.getStr("code").equals("200")) {
                            if (null != detailRes.getJSONArray("data") && !detailRes.getJSONArray("data").isEmpty()) {
                                JSONObject jsonObject = JSONUtil.parseObj(detailRes.getJSONArray("data").get(0)).getJSONObject("detail");
                                String str = jsonObject.getStr("outputTaxRate");
                                if (StringUtils.isNotBlank(str)) {
                                    allocationJson.set("outTaxrate", str);
                                }

                            }
                        }
                        String erpCode = allocationJson.getStr("erpCode");
                        if (StringUtils.isNotBlank(erpCode)){
                            allocationJson.set("erpCode",erpCode);
                        }
                        this.APICurrentLimiting(OpenApiURLEnum.PRODUCT_LIST_BATCHDETAILNEW,59);
                        if (StringUtils.isNotBlank(allocationJson.getStr("outTaxrate"))) {
                            BigDecimal outTaxrate = (BigDecimal) RedisUtils.get(dto.getTenantId() + ":TAX:" + allocationJson.getStr("outTaxrate"));
                            allocationJson.set("outTaxrate_name", outTaxrate);
                        }
                        list.add(allocationJson);
                    }
                }
            }
            this.APICurrentLimiting(OpenApiURLEnum.PRODUCT_FEATURE_LIST,59);
            if (allocationRes.getJSONObject("data").getInt("pageCount") == 0) {
                break;
            }
            if (allocationRes.getJSONObject("data").getInt("pageCount") <= pageIndex) {
                break;
            }
            pageIndex++;
        }
        if (list.size() > 0) {
            for (JSONObject wlObject : list) {
                String ysCode = wlObject.getStr("code");
                RedisUtils.set(dto.getTenantId() + ":product:" + ysCode, wlObject);
                String erpCode = wlObject.getStr("erpCode");
                if (StringUtils.isNotBlank(erpCode)){
                    RedisUtils.set(dto.getTenantId() + ":product:" + erpCode, wlObject);
                }
            }
            logger.info("租户：{} YS系统物料档案同步Redis完成，共同步物料档案：{}条", dto.getTenantId(), list.size());
            InsertLogger(JOB_CLASS,null, "1", "租户：{" + dto.getTenantId() + "} YS系统物料档案同步Redis完成，共同步物料档案：{" + list.size() + "}条");
        }
        return ReturnT.SUCCESS;
    }





}
